<template>
  <div class="orders-container">
    <TableModule :tableModule="tableModule" ref="TableModuleRef" @search="Search" @recover="Recover">
      <!-- 插入的新增按钮和删除按钮 -->
      <template #event>
<!--        <el-button type="primary" @click="Add">新增</el-button>-->
        <el-button type="warning" @click="BatchDelivery">批量发货</el-button>
      </template>
      <!-- 插入表格的操作列 -->
      <template #tableColumn>
        <el-table-column align="center" fixed="right" label="操作" width="170">
          <template #default="scope">
            <el-button @click="Edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="Delete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </TableModule>
    <!--  编辑对话框  -->
    <DialogModule :form-data="dialogModule" ref="dialogModuleRef" @confirm="Confirm" @cancel="Cancel" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, toRefs } from 'vue';
import { columnsData, queryData } from './dataModule/table.ts';
import { formColumns } from "./dataModule/form.ts";
import {
  addOrder,
  getAllOrders,
  getOrderInfoById,
  saveOrderInfo,
  batchDelivery,
  deleteOrder
} from '../../../api/order';
import {ElMessage, ElMessageBox} from "element-plus";
import {Orders} from "../../../api/order/types/orders.dto.ts";

// 表格
const state = reactive({
  columns: columnsData, // 表格配置
  query: queryData, // 查询条件配置
  queryForm: {
    userName: '',
    status: '',
    orderTime: [],
  }, // 查询form表单
  loading: false, // 加载状态
  dataList: [], // 列表数据
  pages: { // 分页数据
    total: 0,
    limit: 20,
    page: 1,
  }
})

const { loading, dataList, columns, pages, query, queryForm } = toRefs(state)

const TableModuleRef = ref() // 表格组件
const dialogModuleRef = ref<any>(null); // 编辑对话框组件

onMounted(() => {
  getDataList(); // 获取列表信息
})

// 传给子组件的
const tableModule = ref({
  callback: getDataList, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
  queryForm: queryForm,
  columns: columns,
  dataList: dataList,
  loading: loading,
  pages: pages,
  query: query,
})

// 获取列表信息
async function getDataList() {
  state.loading = true;
  const res = await getAllOrders({
    page: state.pages.page, limit: state.pages.limit, userName: state.queryForm.userName,
    status: state.queryForm.status, startOrderTime: state.queryForm.orderTime[0], endOrderTime: state.queryForm.orderTime[1]
  });

  state.loading = false;
  if (res.code == 0) {
    state.dataList = res.data;
    state.pages.total = res.count;
  }
}
// 点击查询按钮时触发
function Search() {
  getDataList();
}

// 点击重置按钮时触发
function Recover() {
  state.queryForm = reactive({
    userName: '',
    status: '',
    orderTime: [],
  });
  getDataList();
}

// 新增事件
// function Add() {
//   dialogModule.value.dialogTitle = '新增订单';
//   if (dialogModuleRef.value) {
//     dialogModuleRef.value.showDialog(true);
//   }
// }
// 编辑事件
function Edit(row: any) {
  dialogModule.value.dialogTitle = '编辑订单';
  getFormData(row.orderId);
  if (dialogModuleRef.value) {
    dialogModuleRef.value.showDialog(true);
  }
}

// 删除事件
function Delete(row: any) {
  ElMessageBox.confirm(
      '此操作将永久删除该订单, 是否继续?',
      '提示',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' },
  ).then( async () => {
    const res = await deleteOrder(row.orderId);
    if (res.code == 200) {
      ElMessage({ message: res.message, type: 'success' });
      getDataList();
    } else {
      ElMessage({ message: res.message, type: 'error' });
    }
  }).catch(() => {
    ElMessage({ message: '取消了删除', type: 'info' });
  });
}

// 批量发货
function BatchDelivery() {
  if (TableModuleRef.value.tableRef.getSelectionRows().length == 0) {
    ElMessage({ message: '请选择要发货的订单', type: 'warning' });
    return;
  }
  const statusList = TableModuleRef.value.tableRef.getSelectionRows().map((row: any) => row.status)
  if (statusList.some((status: any) => status !== 1)) {
    ElMessage({ message: '所选订单中存在非待发货状态的订单', type: 'warning' });
    return;
  }
  ElMessageBox.confirm(
      '此操作将把所选订单状态改为配送中, 是否继续?',
      '提示',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' },
  ).then(async () => {
    // 获取选中的订单ID列表
    const selectedIds = TableModuleRef.value.tableRef.getSelectionRows().map((row: any) => row.orderId);
    const res = await batchDelivery(selectedIds);
    if (res.code == 200) {
      ElMessage({ message: res.message, type: 'success' });
      getDataList();
    }
  }).catch(() => {
    ElMessage({ message: '操作失败', type: 'info' });
  });
}

/**
 * 编辑表单模块
 */
const form = reactive({
  formColumn: formColumns
});

const { formColumn } = toRefs(form);

// 传给子组件的
const dialogModule = ref({
  dialogTitle: '',
  inline: false,
  columns: formColumn,
});

// 获取表单信息，用于编辑对话框中显示
async function getFormData(id: number) {
  const res = await getOrderInfoById(id);
  if (res.code == 200) {
    const data = res.data;
    for (let i = 0; i < formColumn.value.length; i++) {
      const prop = formColumn.value[i].prop;
      if (data.hasOwnProperty(prop)) {
        formColumn.value[i].value = data[prop];
      }
    }
  }
}

const Confirm = async (operationType: number) => {
  const formData = dialogModule.value.columns;
  const formValues: { [key: string]: any } = formData.reduce((acc: any, item: any) => {
    acc[item.prop] = item.value;
    return acc;
  }, {});

  console.log("提交数据为:",formValues);

  if (operationType == 1) {
    const res = await addOrder(<Orders>formValues);
    if (res.code == 200) {
      ElMessage({ message: '添加成功', type: 'success' });
    } else {
      ElMessage({ message: '添加失败', type: 'error' });
    }
  } else if (operationType == 2) {
    const res = await saveOrderInfo(<Orders>formValues);
    if (res.code == 200) {
      ElMessage({ message: '保存成功', type: 'success' });
      getDataList();
    } else {
      ElMessage({ message: '保存失败', type: 'error' });
    }
  }
  clearFormValue();
};

const Cancel = () => {
  clearFormValue();
};

// 清空表单 TODO 待优化
const clearFormValue = () => {
  formColumn.value.forEach((item: any) => {
    item.value = '';
  });
};
</script>

<style scoped>
.orders-container {
  padding: 10px;
  background-color: white;
  height: 100%;
}

.diary {
  display: flex;
  align-items: center;
}

.diary:hover {
  cursor: pointer;
  background-color: gainsboro;
}
</style>